﻿using AutoMapper;
using MediatR;
using System.Transactions;
using Traceability.App.Apilication.Common.Slaughter;
using Traceability.App.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure.Interfance;

namespace Traceability.App.Apilication.Handler.Slaughter
{
    public class CreateBreedingHandler : IRequestHandler<CreateBreedingCommon, ApiResult<int>>
    {
        private readonly IBaseRespository<TraceabilityModel> tranceblityRepo;
        private readonly IBaseRespository<BreedingModel> breedingRepo;
        private readonly IMapper mapper;

        public CreateBreedingHandler(IBaseRespository<TraceabilityModel> tranceblityRepo,IBaseRespository<BreedingModel> breedingRepo,IMapper mapper)
        {
            this.tranceblityRepo = tranceblityRepo;
            this.breedingRepo = breedingRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(CreateBreedingCommon request, CancellationToken cancellationToken)
        {
            ApiResult<int> res=new ApiResult<int>();
           
            var model = mapper.Map<BreedingModel>(request);
            
            model.CreateTime = DateTime.Now;
            var r = 0;
            using (TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r= breedingRepo.Add(model).Result;
                tran.Complete();
            }
            if (r > 0)
            {
                res.Code = ApiEnum.Success;
                res.Message = "添加成功";
                return Task.FromResult(res);
            }
            else
            {
                res.Code = ApiEnum.Error;
                res.Message = "添加失败";
                return Task.FromResult(res);
            }



        }
    }
}
